import PubSub from "pubsub-js"
import { useState } from "react"
import "./Item.css"
export default function Item(props) {
  const { todo } = props
  const [isEdit, setIsEdit] = useState(false)
  function handle() {
    PubSub.publish("updateIsDone", todo.id)
  }

  function deleteTodo() {
    PubSub.publish("deleteTodo", todo.id)
  }

  function editTodoBtn() {
    setIsEdit(!isEdit)
  }

  function editTodo(e) {
    if (e.keyCode !== 13) return
    if (!e.target.value.trim()) return (e.target.value = "")
    setIsEdit(!isEdit)
    PubSub.publish("editTodo", [e.target.value.trim(), todo.id])
  }

  function editTodoW(e) {
    if (!e.target.value.trim()) return (e.target.value = "")
    setIsEdit(!isEdit)
    PubSub.publish("editTodo", [e.target.value.trim(), todo.id])
  }
  
  return (
    <li>
      <label>
        {isEdit ? (
          <input type="text" onKeyDown={editTodo} onBlur={editTodoW}/>
        ) : (
          <div>
            <input type="checkbox" checked={todo.isDone} onChange={handle} />
            <span className={props.todo.isDone ? "active" : ""}>
              {props.todo.todoName}
            </span>
          </div>
        )}
      </label>
      <button className="btn btn-danger" onClick={deleteTodo}>
        删除
      </button>
      <button className="btn btn-edit" onClick={editTodoBtn}>
        {isEdit ? "取消" : "编辑"}
      </button>
    </li>
  )
}
